import os
from constants import *
from vm_parser import Parser
from code_writer import CodeWriter
import argparse
import os.path
import glob
from functional import pseq, seq


def translate(file, code_writer):
    srcfile, _ = os.path.splitext(os.path.basename(file))
    with Parser(file) as parser:
        while parser.advance() != "":
            if parser.command_type() == C_ARITHMETIC:
                code_writer.writeArithmetic(parser.arg1())
            elif parser.command_type() == C_PUSH or parser.command_type() == C_POP:
                codeWriter.writePushPop(srcfile,
                                        parser.command_type(), parser.arg1(), parser.arg2())
    return True


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('files', nargs='*', type=str, help='vm files')
    parser.add_argument('--path', nargs='?', type=str, help='vm folder')

    args = parser.parse_args()
    files = seq(args.files).filter(lambda f: f.endswith('.vm')).to_list()
    files.extend(seq(glob.glob("%s/*" % args.path)
                     ).filter(lambda f: f.endswith('.vm')).to_list())
    if files == []:
        print("usage: vm_translator.py [-h] [--path [PATH]] [files ...]")
        exit(1)

    codeWriter = CodeWriter("../MemoryAccess/StaticTest/StaticTest.asm")
    parallel_executor = seq(files)
    parallel_executor.map(lambda file: translate(file, codeWriter)).to_list()
    codeWriter.Close()
